'''
 City Scout: online GIS tool for Technion - Israel Institute of Technology
 Copyright 2012 Israel Institute of Technology - Technion
 The code is licensed under GNU General Public License, v2
  
 File context description:
 Main handlers URI handlers
 
 Author: Sergey N. Bolshchikov
'''

import webapp2
import jinja2
from google.appengine.ext import db

import os
import json

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class Department(db.Model):
    id = db.StringProperty(required = True)
    name = db.StringProperty()
    address = db.StringProperty()
    link = db.LinkProperty()
    

class IndexHandler(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render())

class MapHandler(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('map.html')
        self.response.out.write(template.render())

class EditHandler(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('edit.html')
        self.response.out.write(template.render())

class RPCHandler(webapp2.RequestHandler):
    """ Allows the functions defined in the RPCMethods class to be RPCed."""
#    def __init__(self):
#        webapp2.RequestHandler.__init__(self)
#        self.methods = RPCMethods()
#        logging.warning(RPCHandler.dispatch())
    
    def get(self):
        func = None

        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(RPCMethods(), action, None)

        if not func:
            self.error(404) # file not found
            return

        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (json.loads(val),)
            else:
                break
        result = func(*args)
        self.response.out.write(json.dumps(result))

    def post(self):
        args = json.loads(self.request.body)
        func, args = args[0], args[1:]

        if func[0] == '_':
            self.error(403) # access denied
            return

        func = getattr(RPCMethods(), func, None)
        if not func:
            self.error(404) # file not found
            return

        result = func(*args)
        self.response.out.write(json.dumps(result))


class RPCMethods:
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """
    def addDept(self, *args):
        dept = Department(key_name = args[0][0],
                    id = args[0][0],
                    name = args[0][1],
                    address = args[0][2], 
                    link = args[0][3])
        dept.put()
        response = 'Department ' + dept.name + ' has been added'
        return response  
    
    def getDept(self, *args):
        # The JSON encoding may have encoded integers as strings.
        # Be sure to convert args to any mandatory type(s).
        dept = Department.get_by_key_name(args[0])
        response = dict(
            id = dept.id,
            name = dept.name,
            address = dept.address,
            link = dept.link)
        return response
        
      
app = webapp2.WSGIApplication([('/', IndexHandler),
                               ('/map', MapHandler),
                               ('/edit', EditHandler),
                               ('/rpc', RPCHandler)], debug = True)    
    
def main():
    app.run()
    
if __name__ == "__main__":
    main()